// 编辑页面
import dynamic from 'next/dynamic';
import { getManager } from 'typeorm';
import { GetServerSidePropsContext } from 'next';
import { useRouter } from 'next/router';
import { useState, ChangeEvent, useEffect } from 'react';
import { Input, Button, message, Select } from 'antd';

import requestInstance from '@/service/fetch';
import { prepareConnection } from '@/db';
import { Article } from '@/db/entity';

import '@uiw/react-md-editor/markdown-editor.css';
import '@uiw/react-markdown-preview/markdown.css';
import styles from './new.module.scss'

export const getServerSideProps = async (props: GetServerSidePropsContext) => {
  const articleId = props.params?.id;

  // 数据库连接相关的内容
  const db = await prepareConnection();
  const articleRepo = db.getRepository(Article);
  const article = await articleRepo.findOne({
    where: {
      id: articleId,
    },
    relations: ['user'],
  });

  const queryBuilder = getManager().createQueryBuilder();
  const tableName = 'articles_tags_rel';
  const results = await queryBuilder
    .select(['tag_id', 'article_id'])
    .from(tableName, 't')
    .where('t.article_id = :value', { value: articleId })
    .getRawMany();

  return {
    props: {
      article: JSON.parse(JSON.stringify(article)),
      tags: JSON.parse(JSON.stringify(results))
    },
  };
};

const MDEditor = dynamic(() => import('@uiw/react-md-editor'), { ssr: false });

const ModifyEditor = ({ article, tags }: any) => {
  const [title, setTitle] = useState(article.title || '')
  const [content, setContent] = useState(article.content || '');
  const [allTags, setAllTags] = useState([]);
  const [tagIds, setTagIds] = useState(tags?.map(({ tag_id }: any) => tag_id) || []);
  const { push } = useRouter()

  useEffect(() => {
    getData()
  }, [])

  const getData = async () => {
    const result: any = await requestInstance.get('api/tag/get')
    if (result.code === 200) {
      setAllTags(result.data.allTags || [])
    }
  }

  const handleTitleChange = (event: ChangeEvent<HTMLInputElement>) => {
    setTitle(event?.target?.value);
  };

  const handlePublish = async () => {
    const { id: articleId } = article
    if (!title) {
      message.warning('请输入文章标题')
      return
    }

    const result: any = await requestInstance.post('/api/article/update', {
      title,
      content,
      id: articleId,
      tagIds
    })

    if (result?.code === 200) {
      message.success('更新成功')
      articleId ? push(`/user/${articleId}`) : push('/')
    } else {
      message.error(result?.msg || '更新失败')
    }
  }

  const handleContentChange = (content: any) => {
    setContent(content);
  };

  const handleSelectTag = (value: []) => {
    setTagIds(value)
  }

  return (
    <div className={styles.container}>
      <div className={styles.operation}>
        <Input
          className={styles.title}
          placeholder="请输入文章标题"
          value={title}
          onChange={handleTitleChange}
        />
        <Select
          className={styles.tag}
          mode="multiple"
          allowClear
          placeholder="请选择标签"
          defaultValue={tagIds}
          onChange={handleSelectTag}
        >{allTags.map((tag: any) => (
          <Select.Option key={tag?.id} value={tag?.id}>{tag?.title}</Select.Option>
        ))}</Select>
        <Button
          className={styles.button}
          type="primary"
          onClick={handlePublish}
        >
          更新
        </Button>
      </div>
      <MDEditor value={content} onChange={handleContentChange} height={1080} />
    </div>
  );
};

// 动态控制 layout 显示与否
(ModifyEditor as any).layout = 'invisible';

export default ModifyEditor;
